import AgoraRTC from 'agora-rtc-sdk'
import { Message } from 'element-ui';
import store from '../store/store';

var client = AgoraRTC.createClient({mode: 'live', codec: 'h264'});

client.on('peer-online',function (msg) {
  console.log('peer-online',msg);
});
client.on('peer-leave',function (msg) {
  console.log('peer-leave',msg);
});



client.init(process.env.VUE_APP_AGORA_APP_ID, function () {
  console.log('AgoraRTC client initialized');
}, function (err) {
  console.log('AgoraRTC client init failed', err);
});

export let localStream = null;
export async function rtcLogin(token, channel, uid) {
  return new Promise(((resolve,reject) => {
    console.log('token :::', token, channel, uid);
    client.join(token, channel, 0, function (uid) {
      console.log('User ' + uid + ' join channel successfully');
      resolve();
    }, function (err) {
      console.log('Join channel failed', err);
      reject(err);
    });

    localStream = AgoraRTC.createStream({
      streamID: uid,
      audio: true,
      video: false,
      screen: false,
    });
    localStream.setAudioProfile('speech_standard');
    localStream.init(function () {
      console.log('getUserMedia successfully');
      localStream.play('agora_local');

    }, function (err) {
      console.log('getUserMedia failed', err);
      Message.error({message:'Failed to obtain microphone authorization, please refresh and retry.',duration : 360000})
    });
  }));

}


export function startRecord() {
  //TODO : check user has MIC
  console.log('startRecord');
  client.publish(localStream, function (err) {
    console.log('Publish local stream error: ' + err);
  });
}

export function stopRecord() {
  console.log('stopRecord');
  client.unpublish(localStream, function (err) {
    console.log('Cancel publish local stream error: ' + err);
  });
  localStream.close();
}

let effectSoundArr = [];
export function getEffectSoundId(file){
  if (effectSoundArr.indexOf(file) === -1){
    effectSoundArr.push(file)
  }

  return effectSoundArr.indexOf(file) + 1;
}

export function preloadEffect(file) {
  if(!localStream){
    throw new Error('Please start live streaming first.');
  }

  let effectSoundId = getEffectSoundId(file);

  console.log('preloadEffect',effectSoundId);

  localStream.preloadEffect(effectSoundId, file, function (err) {
    if (err) {
      console.error('Failed to preload effect, reason: ', err);
    } else {
      console.log('Effect is preloaded successfully');
    }
  });
}

export function startAudioMixing(filePath,loop,playTime=0){
  localStream.startAudioMixing({filePath,loop,playTime}, function(err){
    if (err){
      console.log("Failed to start audio mixing. " + err);
    }
  });
}
export function stopAudioMixing() {
  localStream.stopAudioMixing(e=>{
    console.log('stopAudioMixing',e)
  })
}

export function pauseAudioMixing() {
  localStream.pauseAudioMixing(e=>{
    console.log('pauseAudioMixing',e)
  })
}
export function resumeAudioMixing() {
  localStream.resumeAudioMixing(e=>{
    console.log('resumeAudioMixing',e)
  })
}

export function adjustAudioMixingVolume(level) {
  localStream.adjustAudioMixingVolume(level);
}

export function stopEffect(file) {
  localStream.stopEffect(getEffectSoundId(file), function(err){
    if (err){
      console.error("Failed to stop Effect, reason: ", err);
    }else{
      console.log("Effect is stopped successfully");
    }
  });
}
export function playEffect(file) {

  if(!localStream){
    throw new Error('Please start live streaming first.');
  }

  let effectSoundId = getEffectSoundId(file);

  console.log('playEffect',effectSoundId);

  localStream.playEffect({
    soundId: effectSoundId,
    filePath: file
  }, function(error) {
    if (error) {
      throw new Error('Failed to play effect.');
    }
  });
}

client.on('stream-published', function (evt) {
  console.log('Publish local stream successfully');
});

client.on('stream-added', function (evt) {
  var stream = evt.stream;
  console.log('New stream added: ' + stream.getId());

  client.subscribe(stream, function (err) {
    console.log('Subscribe stream failed', err);
  });
});
client.on('stream-subscribed', function (evt) {
  var remoteStream = evt.stream;
  console.log('Subscribe remote stream successfully: ' + remoteStream.getId());
  remoteStream.play('agora_remote');
  remoteStream.setAudioVolume(100);
});
